﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing;

namespace Marta.buchalska.wesele.Admin
{
    class FileMeneger
    {
        readonly string _imageFolder = HttpContext.Current.Server.MapPath("~/img");
        private string _galleryFolder;
        const int OriginalHeight = 502;
        const int OriginalWidth = 550;

        const int MiniHeight = 85;
        const int MiniWidth = 64;

        public string SaveFile(FileUpload postedfile, int galleryId)
        {
            _galleryFolder = new Model.PhotoManager().GetCategoryNameByID(galleryId);
            SaveOriginalFile(postedfile);
            SaveThumbFile(postedfile);

            return string.Format("~/img/{0}/mini-{1}", _galleryFolder, postedfile.FileName);
        }

        private void SaveThumbFile(FileUpload postedfile)
        {
            var image = System.Drawing.Image.FromStream(postedfile.PostedFile.InputStream);

            const int newWidth = MiniWidth;

            const int newHeight = MiniHeight;

            var abort = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

            var thumbnail = image.GetThumbnailImage(newWidth, newHeight, abort, IntPtr.Zero);

            var mo = new MemoryStream();

            thumbnail.Save(mo, image.RawFormat);

            mo.Position = 0;
            // create a write stream
            var writeStream = new FileStream(GalleryMiniPath(postedfile), FileMode.CreateNew, FileAccess.Write);
            // write to the stream
            ReadWriteStream(mo, writeStream);

            thumbnail.Dispose();

            image.Dispose();
        }

        private string GalleryMiniPath(FileUpload postedfile)
        {
            var path = !string.IsNullOrEmpty(_galleryFolder) ? string.Format("{0}\\{1}\\mini-{2}", _imageFolder, _galleryFolder, postedfile.FileName) : string.Format("{0}\\" + "mini-{1}", _imageFolder, postedfile.FileName);
            CheckGalleryPath(path);
            return path;
        }

        private string GalleryOriginallPath(FileUpload postedfile)
        {
            var path = !string.IsNullOrEmpty(_galleryFolder) ? string.Format("{0}\\{1}\\original-{2}", _imageFolder, _galleryFolder, postedfile.FileName) : string.Format("{0}\\original-{1}", _imageFolder, postedfile.FileName);
            CheckGalleryPath(path);
            return path;
        }

        private string CheckGalleryPath(string path)
        {
            var directoryName = Path.GetDirectoryName(path);
            if (Directory.Exists(directoryName))
                return path;
            else
            {
                Directory.CreateDirectory(directoryName);
            }
            return null;
        }

        private static bool ThumbnailCallback()
        {
            return false;
        }

        private void SaveOriginalFile(FileUpload postedfile)
        {
            //mini - 64x85
            //original 550x502
            var mo = new MemoryStream();
            ResizeImage(postedfile.PostedFile.InputStream, mo);
            mo.Position = 0;
            // create a write stream
            var writeStream = new FileStream(GalleryOriginallPath(postedfile), FileMode.CreateNew, FileAccess.Write);
            // write to the stream
            ReadWriteStream(mo, writeStream);
        }

        // readStream is the stream you need to read
        // writeStream is the stream you want to write to
        private void ReadWriteStream(Stream readStream, Stream writeStream)
        {
            int Length = 256;
            Byte[] buffer = new Byte[Length];
            int bytesRead = readStream.Read(buffer, 0, Length);
            // write the required bytes
            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = readStream.Read(buffer, 0, Length);
            }
            readStream.Close();
            writeStream.Close();
        }

        public void ResizeImage(Stream fromStream, Stream toStream)
        {

            var image = System.Drawing.Image.FromStream(fromStream);

            var newWidth = OriginalWidth; //(int)(image.Width * scaleFactor);

            var newHeight = OriginalHeight;//(int)(image.Height * scaleFactor);

            var thumbnailBitmap = new System.Drawing.Bitmap(newWidth, newHeight);

            var thumbnailGraph = System.Drawing.Graphics.FromImage(thumbnailBitmap);

            thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;

            thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;

            thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);

            thumbnailGraph.DrawImage(image, imageRectangle);

            thumbnailBitmap.Save(toStream, image.RawFormat);

            thumbnailGraph.Dispose();

            thumbnailBitmap.Dispose();

            image.Dispose();
        }

        internal void DeleteGallery(string galleryName)
        {
            try
            {
                if (System.IO.Directory.Exists(galleryName))
                    System.IO.Directory.Delete(galleryName, true);
            }
            catch (Exception) { }
        }

        public void DeleteFiles(IEnumerable<string> filePath)
        {
            string tmpPath;
            foreach (string file in filePath)
            {
                tmpPath = HttpContext.Current.Server.MapPath(file);
                File.Delete(tmpPath);
                File.Delete(tmpPath.Replace("mini-", "original-"));
            }
        }

        public void DeleteFile(string filePath)
        {
            File.Delete(HttpContext.Current.Server.MapPath(filePath));
            File.Delete(HttpContext.Current.Server.MapPath(filePath.Replace("mini-", "original-")));
        }
    }
}
